package com.cyl.manager.act.controller;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Page;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.UrlResource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.enums.BusinessType;
import com.alibaba.excel.EasyExcel;
import com.cyl.external.MyEasyExcelUtil;
import com.cyl.manager.act.convert.MemberCouponConvert;
import com.cyl.manager.act.domain.entity.CouponActivity;
import com.cyl.manager.act.domain.entity.MemberCoupon;
import com.cyl.manager.act.domain.query.CouponActivitySy;
import com.cyl.manager.act.domain.query.MemberCouponQuery;
import com.cyl.manager.act.service.CouponActivityService;
import com.cyl.manager.act.service.MemberCouponService;
import com.cyl.manager.aws.domain.entity.ExportExcel;
import com.cyl.manager.act.domain.vo.MemberCouponAddExcelVO;
import com.cyl.manager.act.domain.vo.MemberCouponExcelVO;
import com.cyl.manager.act.domain.vo.MemberCouponVO;
import com.cyl.manager.act.mapper.CouponActivityMapper;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;

import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
/**
 * 用户领券记录Controller
 * 
 * @author zcc
 * @date 2024-03-22
 */
@Api(description ="用户领券记录接口列表")
@RestController
@RequestMapping("/act/memberCoupon")
public class MemberCouponController extends BaseController {
    @Autowired
    private MemberCouponService service;
    @Autowired
    private MemberCouponConvert convert;
    @Autowired
    private CouponActivityMapper couponActivityMapper;
    @Autowired
    private CouponActivityService couponActivityService;
    
    @ApiOperation("查询用户领券记录列表")
    @PostMapping("/list")
    public ResponseEntity<Page<MemberCouponVO>> list(@RequestBody MemberCouponQuery query, Pageable page) {
        Long qrDeptZbjId = SecurityUtils.getDeptZbjId();
        if(qrDeptZbjId!=null) {
        	query.setDeptZbjId(qrDeptZbjId);
        }
        return ResponseEntity.ok(service.selectList(query, page));
    }

    @ApiOperation("获取用户领券记录详细信息")
    @GetMapping(value = "/{id}")
    public ResponseEntity<MemberCoupon> getInfo(@PathVariable("id") Long id) {
        return ResponseEntity.ok(service.selectById(id));
    }

    @ApiOperation("导入发优惠券")
    @Log(title = "导入Excel发优惠券", businessType = BusinessType.INSERT)
    @PostMapping("/addByExcel")
    public ResponseEntity<String> addByExcel(@RequestBody MemberCouponAddExcelVO mcaevo) {
    	

    	 Long couponActivityId = mcaevo.getCouponActivityId(); 
    	 CouponActivity couponActivity = couponActivityService.selectById(couponActivityId);
         if (couponActivity == null) {
             throw new RuntimeException("未找到活动");//中文不能变
         }
      
        //活动未开始或者已经结束
         if(couponActivity.getPublishstatus().intValue() != 1) {
         	throw new RuntimeException("活动未开始或者已经结束");//活动未开始或者已经结束
         }
         //判断时间有没有超
         LocalDateTime now = LocalDateTime.now();
         if (couponActivity.getBeginTime().isAfter(now) || couponActivity.getEndTime().isBefore(now)) {
             throw new RuntimeException("活动已过期");//中文不能变
         }
         
         ExportExcel exportExcel = new ExportExcel(JSONUtil.toJsonStr(mcaevo), "导入Excel发优惠券"+DateUtil.format(new Date(),"yyyyMMddHHmmss")+".xlsx", "导入Excel发优惠券", couponActivityId, mcaevo.getUrl());
         MyEasyExcelUtil<MemberCouponExcelVO> excelVO = new MyEasyExcelUtil<MemberCouponExcelVO>(MemberCouponExcelVO.class,exportExcel,mcaevo.getUrl());
         List<MemberCouponExcelVO> dataList = excelVO.readExcel();
         if(dataList==null) {
             throw new RuntimeException("没有读取到文件内容");
         }
     
         int sumNum = 0;
         Map<Long, Integer> map = new HashMap<Long, Integer>();
 		for (MemberCouponExcelVO data : dataList) {
 			if(map.containsKey(data.getMemberId())) {
 				 String msg = "会员id："+data.getMemberId()+"，重复";
 				 excelVO.error(msg);
				 throw new RuntimeException(msg);
 			}
 			map.put(data.getMemberId(), 1);
 			if(data.getNum() <=0 ) {
 				 String msg = "会员id："+data.getMemberId()+"，发券张数必须大于0";
 				 excelVO.error(msg);
				 throw new RuntimeException(msg);
				 
 			}
 			sumNum = sumNum+data.getNum();
 		}
 	     //判断有没有余量
        if (couponActivity.getLeftCount() < sumNum) {
             String msg = "一共需要发放【"+sumNum+"】张券，但是只有【"+couponActivity.getLeftCount()+"】张。";
			 excelVO.error(msg);
			 throw new RuntimeException(msg);
        }
        
        

        StringBuilder s = new StringBuilder(); 
        boolean bool = false;
		for (MemberCouponExcelVO data : dataList) {
			if(data.getNum()>0) {
				for (int i = 0; i < data.getNum(); i++) {
					try {
						couponActivityService.saveMemberCouponExcel(couponActivity, data.getMemberId(),(0+1),couponActivity.getQlx()+"","后台管理员发券");
					} catch (Exception e) {
						 s.append("会员id："+data.getMemberId()+"，发券失败！"+e.getMessage()+"/n");
						 bool = true;
					}
				}
			}
		}
		
		
		
		if(bool) {
			excelVO.error(s.toString());
	        return ResponseEntity.ok(s.toString());
		}else {
			excelVO.readFinish();
	        return ResponseEntity.ok("操作成功！");
		}
    }
    
    
    @ApiOperation("后台核销优惠券")
    @PostMapping("/exchangeCoupon") ///act/memberCoupon
    @Log(title = "后台核销优惠券", businessType = BusinessType.UPDATE)
    public ResponseEntity<Boolean> exchangeCoupon(@RequestBody CouponActivitySy query) {
        return ResponseEntity.ok(service.exchangeCouponByAdmin(query));
    }
    
    
//
//    @ApiOperation("修改用户领券记录")
//    @Log(title = "用户领券记录", businessType = BusinessType.UPDATE)
//    @PutMapping
//    public ResponseEntity<Integer> edit(@RequestBody MemberCoupon memberCoupon) {
//        return ResponseEntity.ok(service.update(memberCoupon));
//    }
//
//    @ApiOperation("删除用户领券记录")
//    @Log(title = "用户领券记录", businessType = BusinessType.DELETE)
//	@DeleteMapping("/{id}")
//    public ResponseEntity<Integer> remove(@PathVariable Long id) {
//        return ResponseEntity.ok(service.deleteById(id));
//    }
}
